//
//  FirstViewController.m
//  Mayhem
//
//  Created by Jay Meistrich on 5/25/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "FirstViewController.h"
#import "StringEncryption.h"

@implementation FirstViewController

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    
    doesNeedSettings = false;
    
//    self.view = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,480)];
//    self.view.backgroundColor = [UIColor blackColor];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ServiceIPSet:) name:@"ServiceIPSet" object:nil];
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSString *savedIP = [prefs stringForKey:@"IP"];
    if(savedIP != nil)
    {
        NSString *savedPort = [prefs stringForKey:@"Port"];
        [self ConnectToService:savedIP port:savedPort];
    }
    
    /*
    NSURL *url = [NSURL URLWithString:@"http://10.124.137.141:19283/Mayhem/GetHtml"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
    */
    /*
    
    NSString *feedURLString = @"http://10.124.137.141:19283/Mayhem";
    mayhemClient = [[MayhemServiceClient alloc] initWithUrl:feedURLString];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ServiceGetDataCompleted:) name:@"ServiceGetDataCompleted" object:nil];
    
    [mayhemClient GetFormDataAsync:true];

     */
        [super viewDidLoad];
}

- (void)ServiceIPSet: (NSNotification *)notification
{
    NSString *receivedData = [notification object];
    NSLog(@"IP: %@",receivedData);
    
    NSArray *splitSourceData = [receivedData componentsSeparatedByString:@":"];
    
    // This is usually an object that has a series of Array's and Dictionaries to store and organize the incoming data
    NSString *port = [splitSourceData objectAtIndex:0];
    NSString *ip = [splitSourceData objectAtIndex:1];
/*
 NSString *pass = [splitSourceData objectAtIndex:0];
 NSString *port = [splitSourceData objectAtIndex:1];
 NSString *ip = [splitSourceData objectAtIndex:2];

 [StringEncryption setKey:pass];
*/
    

    [self ConnectToService:ip port:port];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ServiceConnected" object:self];

    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    [prefs setObject:ip forKey:@"IP"];
    [prefs setObject:port forKey:@"Port"];
    [prefs synchronize];
//    [self presentModalViewController:self animated:true];
}

- (void)ConnectToService:(NSString*)ip port:(NSString*)port
{
 //   NSString *str = [StringEncryption EncryptString:@"heyeeee bro"];
   // NSString *address = [NSString stringWithFormat:@"http://%@:%@/Mayhem/Login?p=%@",ip,port,str];
    NSString *address = [NSString stringWithFormat:@"http://%@:%@/Mayhem/GetHtml",ip,port];
        NSLog(@"%@",address);

    NSURL *url = [NSURL URLWithString:address];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
}
  /*   
- (void)ServiceGetDataCompleted: (NSNotification *)notification
{
    NSLog(@"event triggered");
    
    NSData *receivedData = [notification object];
    
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    
    NSDictionary *dict = [parser objectWithData:receivedData];
    
    for(id key in dict)
    {
        NSLog(@"key: %@, value: %@",key,[dict objectForKey:key]);
    }
    
    int type = [[dict objectForKey:@"Type"] integerValue];
    
    if(type == 0)
    {
        NSArray *buttonsArray = [dict objectForKey:@"Buttons"];
        for(NSDictionary* obj in buttonsArray)
        {
            int objId = [[obj objectForKey:@"ID"] integerValue];
            NSString *text = [obj objectForKey:@"Text"];
            double x = [[obj objectForKey:@"X"] doubleValue];
            double y = [[obj objectForKey:@"Y"] doubleValue];
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            button.frame = CGRectMake(x, y, 100, 40);
            [button setTitle:text forState:UIControlStateNormal];
            [button setTag:objId];
            [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
            
            [self.view addSubview:button];
            
            for(id key in obj)
            {
                NSLog(@"key: %@, value: %@",key,[obj objectForKey:key]);
            }
        }
    }

}
*/
- (void)buttonPressed:(id)sender
{
    UIButton *button = (UIButton *)sender;
    NSLog(@"Button pressed %d",button.tag);
    NSString* buttonName = [NSString stringWithFormat:@"Button_%d",button.tag];
    [mayhemClient EventAsync:buttonName];
}

- (void)applicationDidFinishLaunching:(UIApplication *)application {
    
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload
{
    [super viewDidUnload];

    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc
{
    [super dealloc];
}

@end
